<template>
	<div class="root">
    <!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-form :inline="true" :model="query" >
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字查询" @click="search"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="add()">新增</el-button>
				</el-form-item>
        <el-form-item style="margin-left: 30px;">
					<el-button type="danger" @click="BatchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>
		</el-col>
    <el-col :span="24">
      <el-table
        v-loading="listLoading"
        :data="pageInfo.rows"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50">
        </el-table-column>
        <el-table-column prop="id" width="50">
        </el-table-column>
        <el-table-column prop="name" label="部门名" width="130">
        </el-table-column>
        <el-table-column prop="manager.username" label="部门经理" width="130">
        </el-table-column>
        <el-table-column prop="parent.name" label="上级部门" width="120">
        </el-table-column>
        <el-table-column prop="intro" label="部门简介" width="180">
        </el-table-column>
        <el-table-column  prop="createTime" label="创建时间" width="180">
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="180">
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.state == 0">正常</el-tag>
            <el-tag type="danger" v-if="scope.row.state == 1">禁止</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" @click="update(scope.row)" >编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="small" @click="deleteById(scope.row.id)"/>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="24" style="margin-top: 20px;">
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[5, 10]"
      :page-size="query.rows"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>
    </el-col>
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio v-model="saveForm.state" label="0">正常</el-radio>
          <el-radio v-model="saveForm.state" label="1">禁止</el-radio>
				</el-form-item>
				<el-form-item label="部门经理" prop="manager">
					<el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<el-cascader v-model="saveForm.parent.id" placeholder="请选择"
							:options="deptTree"
							:props="{
                children:'children',
							  checkStrictly: true,
							  label:'name',
							  value:'id'
							}"
							clearable></el-cascader>
				</el-form-item>
        <el-form-item label="部门简介">
          <el-input type="textarea" v-model="saveForm.intro"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

  </div>
		
</template>

<script>
  import depApi from '@/api/org/department'
  import empApi from '@/api/org/employee'
	export default {
		data() {
			return {
				//分页相关
				query:{
					page:1,
					rows:5,
					keyword:''
				},
				pageInfo:{
					total:0, //总记录数
					rows:[] //表数据
				},
        saveFormVisible:false,
				listLoading: true,
        ids:[], //选中的数据
        saveFormRules: {
					name: [
						{ required: true, message: '请输入名字', trigger: 'blur' }
					]
				},
        saveForm: {
					name: "",
					intro:"",
          manager:{
					  id:null,
            username:""
          },
          parent:{
					  id:null,
            name:""
          },
          state:null
				},
        employees:[],
        deptTree:[],
        saveLoading:false
			}
		},
    created(){

    },
		methods: {
			search(){
        this.getListPage()
      },
      getAllEmp(){
        empApi.getAllEmp()
          .then(response => {
            this.employees = response.data.resultObj
          })
      },
      getDepTree(){
        depApi.getDepTree()
          .then(response => {
            this.deptTree = response.data.resultObj
          })
      },
      //分页查询
      getListPage(){
        this.listLoading = true
        depApi.listPageByQuery(this.query)
          .then(response => {
            this.pageInfo = response.data.resultObj
            setTimeout(() => {
              this.listLoading = false
            },350)
          })
      },
      //全选回调函数
      handleSelectionChange(value){
        this.ids = []
        value.forEach(d => {
          this.ids.push(d.id)
        });
      },
      //每页条数发生改变的回调函数
      handleSizeChange(pageTotals){
        this.query.rows = pageTotals
        this.getListPage()
      },
      //当前页发生改变的回调函数
      handleCurrentChange(curentPage){
        this.query.page = curentPage
        this.getListPage()
      },
      add(){
        this.saveFormVisible = true
        this.saveForm = {
					name: null,
					intro:null,
          manager:{
					  id:null,
            username:null
          },
          parent:{
					  id:null,
            name:null
          },
          state:null
				}
        this.getAllEmp()
        this.getDepTree()
      },
      update(row){
        this.saveFormVisible = true
        this.saveForm = row
        if(this.saveForm.parent == null){
          this.saveForm.parent = {id:null}
        }
        if(!this.saveForm.manager == null){
          this.saveForm.manager = {id:null}
        }
        this.getAllEmp()
        this.getDepTree()
        // let path = row.path
        // let ids = path.split("/")
        // let temp = []
        // for(let i = 1; i < ids.length-1; i++){
        //   temp.push(parseInt(ids[i]))
        // }
        // this.saveForm.parent.id = temp
      },
      //保存修改
      saveSubmit(){
        this.listLoading = true
        let parent = this.saveForm.parent
        if(parent && parent.length > 0){
          this.saveForm.parent = {id:parent[parent.length-1]}
        }
        depApi.insertDep(this.saveForm)
          .then(response => {
            this.$message.success("保存成功！");
            this.saveFormVisible = false
            this.listLoading = false
            this.getListPage()
          })
      },
      //通过id删除租户类型
      deleteById(id){
        this.$confirm('此操作将永久删除该部门信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          depApi.deleteDepById(id)
          .then(response => {
            this.$message.success("删除成功！");
            this.getListPage()
          }).catch(response => {this.$message.error("删除失败！");})
        }).catch(() => {
          this.$message.info("已取消删除");         
        });
      },
      //批量删除
      BatchDelete(){
        this.$confirm('此操作将永久删除该部门信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.ids.length < 1){
            this.$message.warning("请选要删除的部门！");
          }else{
            depApi.batchDelete(this.ids)
              .then(response =>{
                this.$message.success("批量删除成功！");
                this.getListPage()
              }).catch(response => {
                this.$message.error("批量删除失败！");
              })
          }
        }).catch(() => {
          this.$message.info("已取消删除");  
        })
      }
		},
		mounted() {
      this.getListPage()
		}
	}

</script>

<style scoped>
  
.root{
  margin: 30px 16px;
}
.toolbar{
  background-color: rgb(244, 243, 244);
  padding-top: 10px;
  padding-left: 10px;
  height: 60px;
}
</style>